òɾۿûѧϰʹá
ԭַhttps://www.joinquant.com/post/13065

ԭһ˵ʽ鵽ԭĺ߽ۡ


ԭĲԴ£

# ¡Ծۿ£https://www.joinquant.com/post/10272
# ⣺áRSRS(֧ǿ)ʱԣ£
# ߣJoinQuant

# ¡Ծۿ£https://www.joinquant.com/post/10246
# ⣺áRSRS(֧ǿ)ʱԣ£
# ߣJoinQuant

# 뺯
import statsmodels.api as sm
from pandas.stats.api import ols

# ʼ趨׼ȵ
def initialize(context):
    # 趨ָ֤Ϊ׼
    set_benchmark('000300.XSHG')
    # ̬Ȩģʽ(ʵ۸)
    set_option('use_real_price', True)
    # ݵ־ log.info()
    log.info('ʼʼȫֻһ')
    # ˵orderϵAPIıerror͵log
    # log.set_level('order', 'error')
    
    ### Ʊ趨 ###
    # ƱÿʽʱǣʱӶ֮ʱӶ֮ǧ֮һӡ˰, ÿʽӶͿ5Ǯ
    set_order_cost(OrderCost(close_tax=0.001, open_commission=0.0003, close_commission=0.0003, min_commission=5), type='stock')
    
    ## кreference_securityΪʱĲοģıֻ֣˴'000300.XSHG''510300.XSHG'һģ
      # ǰ
    run_daily(before_market_open, time='before_open', reference_security='000300.XSHG') 
      # ʱ
    run_daily(market_open, time='open', reference_security='000300.XSHG')
      # ̺
    run_daily(after_market_close, time='after_close', reference_security='000300.XSHG')

    # RSRSָN, Mֵ
    g.N = 18
    g.M = 1100
    g.init = True
    
    # ҪĹƱƽУg.Ϊȫֱ
    g.security = '160706.XSHE'
    
    # ֵ
    g.buy = 0.7
    g.sell = -0.7
    g.ans = []
    g.ans_rightdev= []
    
    # 200515ز⿪ʼڵRSRSбָ
    prices = get_price(g.security, '2005-01-05', context.previous_date, '1d', ['high', 'low'])
    highs = prices.high
    lows = prices.low
    g.ans = []
    for i in range(len(highs))[g.N:]:
        data_high = highs.iloc[i-g.N+1:i+1]
        data_low = lows.iloc[i-g.N+1:i+1]
        X = sm.add_constant(data_low)
        model = sm.OLS(data_high,X)
        results = model.fit()
        g.ans.append(results.params[1])
        #r2
        g.ans_rightdev.append(results.rsquared)
        
    
## ǰк     
def before_market_open(context):
    # ʱ
    log.info('ʱ(before_market_open)'+str(context.current_dt.time()))

    # ΢ŷϢģ⽻ף΢Ч
    send_message('õһ~')

    
## ʱк
def market_open(context):
    log.info('ʱ(market_open):'+str(context.current_dt.time()))
    security = g.security
    # ȡõǰֽ
    cash = context.portfolio.available_cash

    # ڵRSRSбֵ

    security = g.security
    beta=0
    r2=0
    
    if g.init:
        g.init = False
    else:
        # RSRSбָ궨
        prices = attribute_history(security, g.N, '1d', ['high','low','volume'])
        highs = prices.high
        lows = prices.low
        
        X = sm.add_constant(lows)
        model = sm.OLS(highs, X)
        beta = model.fit().params[1]
        g.ans.append(beta)
        #r2
        r2=model.fit().rsquared
        g.ans_rightdev.append(r2)
    # ׼RSRSָ
    # ֵ 

    h = attribute_history(security,g.N, '1d', ['volume'])
    volume=h.volume
    #cut = g.ans[-g.M:]
    #section=[cut[i]*(volume[i]/sum(volume)*g.N) for i in range(g.N)]
    section = g.ans[-g.M:]
    # ֵ
    mu = np.mean(section)
    # ׼RSRSָ
    sigma = np.std(section)
    zscore = (section[-1]-mu)/sigma  
    #ƫRSRS׼
    #zscore_rightdev= zscore*beta*r2
    #zscore_rightdev= zscore*(sum(volume[-1])/sum(volume)*g.N)
    zscore_rightdev= zscore*beta*r2*(sum(volume[-9:])/sum(volume)*g.N/len(volume[-9:]))
    print(zscore_rightdev)
    # һʱRSRSбʴֵ, ȫ
    if zscore_rightdev > g.buy:
        # ¼
        log.info("׼RSRSбʴֵ,  %s" % (security))
        #  cash Ʊ
        order_value(security, cash)
    # һʱRSRSбСֵ, ղ
    elif zscore_rightdev < g.sell and context.portfolio.positions[security].closeable_amount > 0:
        # ¼
        log.info("׼RSRSбСֵ,  %s" % (security))
        # йƱ,ʹֻƱճΪ0
        order_target(security, 0)
 
## ̺к  
def after_market_close(context):
    log.info(str('ʱ(after_market_close):'+str(context.current_dt.time())))
    #õгɽ¼
    trades = get_trades()
    for _trade in trades.values():
        log.info('ɽ¼'+str(_trade))
    log.info('һ')
    log.info('##############################################################')